package com.jhgsys.internal.hazard.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.hazard.constant.HazardConstant;
import com.jhgsys.internal.hazard.dto.HazardReportDto;
import com.jhgsys.internal.hazard.entity.HazardReport;
import com.jhgsys.internal.hazard.service.IHazardReportAuditRecordService;
import com.jhgsys.internal.hazard.service.IHazardReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author wanghw
 * @CreateTime 2024/8/21 15:59
 * @Description 隐患制定计划
 * @Version 1.0
 */
@Slf4j
@Validated
@Controller
public class HazardReportPlanController  extends BaseController {
    @Autowired
    private IHazardReportService hazardReportService;



    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardReportPlan")
    @RequiresPermissions("hazardReportPlan:view")
    public String hazardReportPlanIndex(Model model){
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("tenantList",getTenantList());
        model.addAttribute("currentTenantId", getCurrentTenantId());
        return FebsUtil.view("hazard/hazardReportPlan/hazardReportPlanList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardReportPlan/plan/{id}")
    @RequiresPermissions("hazardReportPlan:plan")
    public String hazardReportUpdate(Model model, @PathVariable("id") String id) throws JsonProcessingException {
        HazardReportDto dto = hazardReportService.findHazardReportById(id);
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("hazardReport", JSON.parse(new ObjectMapper().writeValueAsString(dto)));
        model.addAttribute("currentTenantId", getCurrentTenantId());
        return FebsUtil.view("hazard/hazardReportPlan/hazardReportPlanEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardReportPlan/message/{id}")
    @RequiresPermissions("hazardReportPlan:plan")
    public String hazardReportPlanMessage(Model model, @PathVariable("id") String id) throws JsonProcessingException {
        HazardReportDto dto = hazardReportService.findHazardReportById(id);
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("hazardReport", dto);
        model.addAttribute("currentTenantId", getCurrentTenantId());
        model.addAttribute("currentUser",getCurrentUser());
        return FebsUtil.view("hazard/hazardReportMessage/hazardReportMessageReply");
    }

    /**
     * 制定计划查询（分页）
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @GetMapping("hazardReportPlan/list")
    @ResponseBody
    @RequiresPermissions("hazardReportPlan:view")
    public FebsResponse hazardReportList(QueryRequest request, HazardReportDto hazardReport) {
        List<String> statusList = Arrays.asList(HazardConstant.HAZARD_STATUS.PLAN,HazardConstant.HAZARD_STATUS.BACK_RECTIFICATION);
        hazardReport.setStatus(statusList.stream().collect(Collectors.joining(StringPool.COMMA)));
        Map<String, Object> dataTable = getDataTable(this.hazardReportService.findHazardReportPage(request, hazardReport));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 新增 整改计划
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @Log("新增隐患上报")
    @PostMapping("hazardReportPlan")
    @ResponseBody
    @RequiresPermissions("hazardReportPlan:plan")
    public FebsResponse addHazardReport(@RequestBody  HazardReportDto hazardReport) throws FebsException {
        checkParams(hazardReport);
        try {
            HazardReport report = hazardReportService.findHazardReportById(hazardReport.getReportId());
            if(ObjectUtils.isEmpty(report)){
                return new FebsResponse().fail().message("待整改的隐患信息不存在!");
            }
            if (!HazardConstant.HAZARD_STATUS.PLAN.equals(report.getStatus()) &&
                  !HazardConstant.HAZARD_STATUS.BACK_RECTIFICATION.equals(report.getStatus())){
                return new FebsResponse().fail().message("待整改的隐患信息已经制定过计划！");
            }
            hazardReport.setUpdatedBy(getCurrentUser().getUserName());
            hazardReport.setUpdatedTime(new Date());
            hazardReport.setPlanDate(new Date());
            hazardReport.setPlanFormulateUserId(getCurrentUser().getUserId());
            hazardReport.setPlanUserNo(getCurrentUser().getUserNo());
            hazardReport.setPlanUserDeptId(getCurrentUser().getDeptId());
            hazardReport.setPlanFormulateName(getCurrentUser().getUname());
            hazardReport.setPlanUserDeptName(getCurrentUser().getDeptName());
            this.hazardReportService.createHazardReportPlanRecord(hazardReport,getCurrentUser(),report.getStatus());
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增整改计划失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 新增 整改计划
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @Log("隐患转发审核")
    @PostMapping("auditForwardTo")
    @ResponseBody
    @RequiresPermissions("hazardReportPlan:plan")
    public FebsResponse auditForwardTo(@RequestBody  HazardReportDto hazardReport) throws FebsException {
        try {
            HazardReport report = hazardReportService.findHazardReportById(hazardReport.getReportId());
            if(ObjectUtils.isEmpty(report)){
                return new FebsResponse().fail().message("待整改的隐患信息不存在!");
            }
            if (!HazardConstant.HAZARD_STATUS.PLAN.equals(report.getStatus())){
                return new FebsResponse().fail().message("待整改的隐患信息已经制定过计划！");
            }
            hazardReport.setUpdatedBy(getCurrentUser().getUserName());
            hazardReport.setUpdatedTime(new Date());
            hazardReport.setStatus(HazardConstant.HAZARD_STATUS.RECTIFICATION);
            hazardReport.setForwardFlg(HazardConstant.FORWARD_FLG.FORWARD_DONE);
            if(HazardConstant.HAZARD_IS_OR_NO.IS.equals(hazardReport.getForwardAuditStatus())){
                hazardReport.setLeaderId(report.getForwardToUserId());
                hazardReport.setLeaderNo(report.getForwardToUserNo());
                hazardReport.setLeaderName(report.getForwardToUserName());
                hazardReport.setLeaderDeptId(report.getForwardToUserDeptId());
                hazardReport.setLeaderDeptName(report.getForwardToUserDeptName());
            }
            this.hazardReportService.auditForwardToHazardReport(hazardReport,getCurrentUser());
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增整改计划失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    private void checkParams(HazardReportDto hazardReport) throws FebsException {

        if(StringUtils.isBlank(hazardReport.getReportId())){
            throw new FebsException("隐患报告Id不能为空");
        }
        if(StringUtils.isBlank(hazardReport.getStatus())){
            throw new FebsException("隐患报告状态不能为空");
        }
        if(HazardConstant.HAZARD_STATUS.RECTIFICATION.equals(hazardReport.getStatus())){
            if(StringUtils.isBlank(hazardReport.getHazardOperation())){
                throw new FebsException("隐患类型不能为空");
            }
            if(ObjectUtils.isEmpty(hazardReport.getRectificationDate())){
                throw new FebsException("截至日期不能为空");
            }
            if(StringUtils.isBlank(hazardReport.getUnsafeName())){
                throw new FebsException("不安全行为或状态不能为空");
            }
            if(StringUtils.isBlank(hazardReport.getLeaderId())){
                throw new FebsException("责任人Id不能为空");
            }
            if(StringUtils.isBlank(hazardReport.getLeaderName())){
                throw new FebsException("责任人姓名不能为空");
            }
            if(StringUtils.isBlank(hazardReport.getLeaderNo())){
                throw new FebsException("责任人工号不能为空");
            }
            if(StringUtils.isBlank(hazardReport.getRectificationMeasures())){
                throw new FebsException("整改措施不能为空");
            }
            if(StringUtils.isBlank(hazardReport.getProjectId())){
                throw new FebsException("项目Id不能为空");
            }
            if(StringUtils.isBlank(hazardReport.getProjectName())){
                throw new FebsException("项目名称不能为空");
            }
            if(StringUtils.isBlank(hazardReport.getAreaId())){
                throw new FebsException("位置区域Id不能为空");
            }
            if(StringUtils.isBlank(hazardReport.getAreaName())){
                throw new FebsException("位置区域不能为空");
            }
        }else {
            if(StringUtils.isBlank(hazardReport.getRectificationMeasures())){
                throw new FebsException("退回理由不能为空");
            }
            hazardReport.setHazardOperation(null);
            hazardReport.setRectificationDate(null);
            hazardReport.setUnsafeName(null);
            hazardReport.setLeaderName(null);
            hazardReport.setLeaderNo(null);
            hazardReport.setLeaderDeptId(null);
            hazardReport.setLeaderDeptName(null);
            hazardReport.setLeaderId(null);
        }





    }
}
